<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="方案名称" prop="fPlanName">
        <el-input v-model="queryParams.fPlanName" placeholder="请输入方案名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="添加日期">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
          range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['wf:plan:add']">新增</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="planList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="方案编码" align="center" prop="fPlanCode" />
      <el-table-column label="方案名称" align="center" prop="fPlanName" />
      <el-table-column label="方案介绍" align="center" prop="fRemark" />
      <el-table-column label="状态" align="center" prop="fForbidStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.fForbidStatus" />
        </template>
      </el-table-column>
      <el-table-column label="添加人" align="center" prop="fCreaterName" />
      <el-table-column label="添加日期时间" align="center" prop="fCreateDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.fCreateDate,'{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后修改人" align="center" prop="fModifierName" />
      <el-table-column label="最后修改时间" align="center" prop="fModifyDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.fModifyDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>

      <el-table-column fixed="right" label="操作" align="center" class-name="small-padding fixed-width" min-width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row, 1)"
            v-hasPermi="['wf:plan:edit']">查看</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['wf:plan:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['wf:plan:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改NA-B方案管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="方案编码" prop="fPlanCode">
              <el-input v-model="form.fPlanCode" placeholder="请输入方案编码" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="方案名称" prop="fPlanName">
              <el-input v-model="form.fPlanName" placeholder="请输入方案名称" :disabled="isEdit == 1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否启用" prop="fForbidStatus">
              <el-radio-group v-model="form.fForbidStatus" :disabled="isEdit == 1">
                <el-radio v-for="dict in fForbidStatus" :key="dict.value" :label="dict.value">{{ dict.label
                  }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="方案介绍" prop="fRemark">
          <el-input type="textarea" v-model="form.fRemark" placeholder="请输入介绍" :disabled="isEdit == 1" />
        </el-form-item>
        <el-divider content-position="center">NA-B方案管理信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddWfPlanDetail"
              v-if="isEdit != 1">添加</el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWfPlanDetail">删除</el-button>
          </el-col> -->
        </el-row>
        <el-table style="width:100%;" :data="form.wfPlanDetailList" :row-class-name="rowWfPlanDetailIndex"
          @selection-change="handleWfPlanDetailSelectionChange" ref="wfPlanDetail">
          <el-table-column type="selection" width="150" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="100" :disabled="isEdit == 1" />

          <el-table-column label="驱动板等待时间(秒)" align="center" prop="fDriverWaitTime" width="150">
            <template slot-scope="scope" :disabled="isEdit == 1">
              <el-input :value="scope.row.wfDriverWait ? scope.row.wfDriverWait.fDriverWaitTime : ''"
                @focus="openAdd(scope.$index)" placeholder="请选择驱动板等待时间" :disabled="isEdit == 1" />
            </template>
          </el-table-column>
          <el-table-column label="刷新图片" align="center" prop="fPictureUrl" width="200">
            <template slot-scope="scope">
              <el-button v-if="!scope.row.fPictureUrl" @click="uploadFile(scope.$index)" size="mini"
                type="primary">选取文件</el-button>
              <div v-else>
                <el-link @click="uploadFile(scope.$index)" :underline="false" target="_blank">
                  <span class="el-icon-document"> {{ scope.row.fPictureUrl ? getFileName(scope.row.fPictureUrl) : '' }}
                  </span>
                </el-link>
                <a style="color: #2561EF;" target="_blank" :download="getFileName(scope.row.fPictureUrl)"
                  :href="scope.row.fPictureUrl" :name="getFileName(scope.row.fPictureUrl)">下载</a>
              </div>
              <!-- <FileUpload :value="scope.row.fPictureUrl" :limit="1" :isShowTip="false"
                @input="uploadFile($event, scope.$index)" :fileType="['bin']" :disabled="isEdit == 1"></FileUpload> -->
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" prop="fRemark" width="200">
            <template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteWfPlanDetail(scope.$index)"
                v-if="isEdit != 1">删除</el-button>
            </template>
          </el-table-column>

        </el-table>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-if="isEdit != 1">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="驱动板等待时间" :visible.sync="dialogFormVisible" append-to-body width="80%">
      <addProw @closeDrawer="closeDrawer" @confirmDrawer="confirmDrawer"></addProw>
    </el-dialog>
    <el-dialog :visible.sync="showUploadImg" title="选择文件" width="70%">
      <uploadImg @close="showUploadImg = false" @sure="getImg"></uploadImg>
    </el-dialog>
  </div>
</template>

<script>
import { listPlan, getPlan, delPlan, addPlan, updatePlan } from "@/api/basicData/plan";
import addProw from './components/addProw.vue';
export default {
  components: {
    addProw
  },
  name: "Plan",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      dialogFormVisible: false,
      dateRange: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedWfPlanDetail: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // NA-B方案管理表格数据
      planList: [],
      // NA-B方案管理表格数据
      // wfPlanDetailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fPlanCode: null,
        fPlanName: null,
        fRemark: null,
      },
      // 表单参数
      form: {
        fEnabled: false,
        wfPlanDetailList: [],
        fForbidStatus: 0
      },
      // 表单校验
      rules: {
        fForbidStatus: [
          { required: true, message: "请选择是否启用不能选空", trigger: "change" }
        ],
        fPlanName: [
          { required: true, message: "方案名称不能为空", trigger: "change" }
        ],
        fDriverWaitTime: [
          { required: true, message: "驱动板等待时间不能为空", trigger: "change" }
        ],
        fPictureUrl: [
          { required: true, message: "驱动板等待时间不能为空", trigger: "change" }
        ],
      },
      fForbidStatus: [
        { value: 0, label: '启用' },
        { value: 1, label: '停用' }
      ],
      waitIndex: 0,
      isEdit: 0,
      imgIndex: 0,
      showUploadImg:false
    };
  },
  created() {
    this.getList();
  },
  computed: {
    statusText() {
      return this.form.fEnabled ? '开启' : '关闭';
    }
  },
  methods: {
    getImg(e) {
      console.log(e)
      this.showUploadImg = false
      this.form.wfPlanDetailList[this.imgIndex].fPictureUrl = e.fPictureUrl
      this.form.wfPlanDetailList[this.imgIndex].fPictureId = e.fId
      this.form.wfPlanDetailList[this.imgIndex].fUrlState = this.form.wfPlanDetailList[this.imgIndex].fPictureUrl ? 1 : 0
    },
    uploadFile(index) {
      if(this.isEdit==1)return
      this.imgIndex = index;
      this.showUploadImg = true
    },
    getFileName(name) {
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    openAdd(index) {
      console.log('www')
      this.waitIndex = index
      this.dialogFormVisible = true
    },
    closeDrawer() {
      this.dialogFormVisible = false;
    },
    confirmDrawer(e) {
      this.dialogFormVisible = false;
      this.form.wfPlanDetailList[this.waitIndex].wfDriverWait.fMinute = e.fId
      this.form.wfPlanDetailList[this.waitIndex].wfDriverWait.fDriverWaitTime = e.fDriverWaitTime
      this.$set(this.form.wfPlanDetailList, this.waitIndex, { ...this.form.wfPlanDetailList[this.waitIndex], fMinute: e.fId });
      this.$set(this.form.wfPlanDetailList, this.waitIndex, { ...this.form.wfPlanDetailList[this.waitIndex], fDriverWaitTime: e.fDriverWaitTime });
      // this.wfPlanDetailList.push({...e})
      // this.form.fProductName = e.fProductName
      // this.form.fDeviceModel = e.fDeviceModel
      // this.form.fProductId = e.fId
      // this.form.fForbidStatus = e.fForbidStatus
    },
    // 添加日期范围到查询参数
    addDateRange(params, dateRange) {
      params.fCreateDateStart = dateRange[0];
      params.fCreateDateEnd = dateRange[1];
      return params;
    },
    /** 查询NA-B方案管理列表 */
    getList() {
      this.loading = true;
      listPlan(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.planList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    handleSwitchChange(value) {
      console.log('开关状态：', value ? '开启' : '关闭');
    },
    // 表单重置
    reset() {
      this.form = {
        fId: null,
        fPlanCode: null,
        fPlanName: null,
        fRemark: null,
        dateRange: null,
        fForbidStatus: 0
      };
      this.form.wfPlanDetailList = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isEdit = 0
      this.reset();
      this.open = true;
      this.title = "添加NA-B方案管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row, type) {
      this.isEdit = type
      this.reset();
      const fId = row.fId || this.ids
      getPlan(fId).then(response => {
        this.form = response.data;
        this.form.wfPlanDetailList = response.data.wfPlanDetailList;
        this.open = true;
        if (type === 1) {
          this.open = true;
          this.title = "查看NA-B方案管理";
        } else {
          this.open = true;
          this.title = "修改NA-B方案管理";
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // this.form.wfPlanDetailList = this.wfPlanDetailList;
          if (this.form.fId != null) {
            updatePlan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPlan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fIds = row.fId || this.ids;
      this.$modal.confirm('是否确认删除NA-B方案管理编号为"' + fIds + '"的数据项？').then(function () {
        return delPlan(fIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** NA-B方案管理序号 */
    rowWfPlanDetailIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** NA-B方案管理添加按钮操作 */
    handleAddWfPlanDetail() {
      let obj = {};
      obj.fPlanOrder = "";
      obj.fMinute = "";
      obj.fPictureUrl = "";
      obj.fRemark = "";
      obj.wfDriverWait = {};
      this.form.wfPlanDetailList.push(obj);
    },
    /** NA-B方案管理删除按钮操作 */
    handleDeleteWfPlanDetail(index) {
      this.form.wfPlanDetailList.splice(index, 1);
      // if (this.form.checkedWfPlanDetail.length == 0) {
      //   this.$modal.msgError("请先选择要删除的NA-B方案管理数据");
      // } else {
      //   const wfPlanDetailList = this.form.wfPlanDetailList;
      //   const checkedWfPlanDetail = this.checkedWfPlanDetail;
      //   this.form.wfPlanDetailList = wfPlanDetailList.filter(function(item) {
      //     return checkedWfPlanDetail.indexOf(item.index) == -1
      //   });
      // }
    },
    /** 复选框选中数据 */
    handleWfPlanDetailSelectionChange(selection) {
      this.checkedWfPlanDetail = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wf/plan/export', {
        ...this.queryParams
      }, `plan_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
